package cn.tang.tframe.dynconfig;

import cn.tang.tframe.common.utils.lang.CollectionUtils;
import cn.tang.tframe.common.utils.lang.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * Created by tanghc on 17/1/23.
 */
public class ZkCopy {
	static CuratorFramework from = createClient("localhost:2181");
	static CuratorFramework to = createClient("localhost:2182");

	public static void main(String[] args) throws Exception {
		doCopy("/configs");
		doCopy("/startconfigs");
	}
	public static CuratorFramework createClient(String url){
		CuratorFramework client = CuratorFrameworkFactory.newClient(url, new ExponentialBackoffRetry(1000, 3));
		client.start();
		return client;
	}
	public static void doCopy(String node) throws Exception {
		if(StringUtils.isNotBlank(node)){
			System.out.println("======= docopy ======"+node);
			if(from.checkExists().forPath(node) != null){
				byte[] bytes = from.getData().forPath(node);
				Stat stat = to.checkExists().forPath(node);
				if(null == stat){
					to.create().forPath(node,bytes);
				}else{
					to.setData().forPath(node,bytes);
				}
			}
			List<String> strings = from.getChildren().forPath(node);
			if(CollectionUtils.isNotEmpty(strings)){
				for(String c: strings){
					doCopy(node+"/"+c);
				}
			}
		}
	}
}
